<template>
  <el-dialog
    v-model="visible"
    title="更新代理商配置"
    width="600px"
    @close="resetForm"
  >
    <el-form
      ref="userFormRef"
      label-position="top"
      :model="form"
      :rules="rules"
    >
      <el-form-item label="支付地址" prop="walletAddress">
        <el-input v-model="form.walletAddress" placeholder="请输入支付地址" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { message } from "@/utils/message";
import { updateAdminAgentsPaymentConfig } from "@/api/adminAgentApi";
interface UserForm {
  walletAddress: string;
}

const visible = ref(false);
const agentId = ref("");
const form = reactive<UserForm>({
  walletAddress: ""
});

const emits = defineEmits(["refresh"]);

const rules: FormRules = {
  walletAddress: [
    { required: true, message: "请输入支付地址", trigger: "blur" }
  ]
};

const userFormRef = ref<FormInstance>();

const submitForm = () => {
  userFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        const { message: text } = await updateAdminAgentsPaymentConfig(
          agentId.value,
          form
        );
        message(text || "更新成功", { type: "success" });
        visible.value = false;
        emits("refresh");
      } catch (error) {
        console.error(error);
      }
    }
  });
};

const resetForm = () => {
  userFormRef.value?.resetFields();
};

const open = (data: any) => {
  agentId.value = data.agentId;
  form.walletAddress = data.paymentWalletAddress;
  visible.value = true;
};

defineExpose({ open });
</script>
